"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   :  配置文件丢失恢复后，备机重建full模式
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1. 备机删除配置文件
    2. 备机重建
    3. 备机恢复配置文件
    4. 备机删除数据目录
    5. 备机重建
    6. 备机数据文件损坏
    7. 备机重建
Expect      :
    1. 执行成功，无返回信息
    2. 执行失败，返回
    3. 执行成功，无返回信息
    4. 执行成功，无返回信息
    5. 执行成功，返回
    6. 执行成功，无返回
    7. 执行成功，返回
History     :
    modified: 2021/01/08  modified by @wan005,优化环境恢复
    modified: 2021/01/22  modified by @wan005,使用库函数替换脚本中build操作
    modified: 2021/02/26  modified by @wan005,tearDown中增加备机重建，防止对后续用例影响
"""
import os
import unittest
from yat.test import Node
import time
from yat.test import macro

from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import *

logger = Logger()


class Stop_immediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbStandby1UserNode = Node(node='Standby1DbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    commonsh_user = CommonSH('PrimaryDbUser')
    conffile = os.path.join(macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
    conffilebak = os.path.join(macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME + '.baktest')
    basefile = os.path.join(macro.DB_INSTANCE_PATH, '/base')
    basefilebak = basefile + '.baktest'
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.constant = Constant()
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case175.py start------------')

    def test_stop_immediate(self):
        logger.info("------------------delete conf file----------------------")
        deleteCmd = f'mv {self.conffile} {self.conffilebak}'
        logger.info(deleteCmd)
        self.dbStandby1UserNode.sh(deleteCmd)
        logger.info(self.dbStandby1UserNode.sh(f'ls -al {macro.DB_INSTANCE_PATH}').result())

        logger.info("------------------build standby----------------------")
        result = self.standby_1_sh.buildStandby()
        logger.info(result)
        self.assertIn(self.constant.BUILD_FAIL_MSG_OPEN, result)

        time.sleep(5)

        logger.info("------------------------recover conf file------------------")
        recoverCmd = f'mv {self.conffilebak} {self.conffile}'
        logger.info(recoverCmd)
        self.dbStandby1UserNode.sh(recoverCmd)
        logger.info(self.dbStandby1UserNode.sh(
            f'ls -al {macro.DB_INSTANCE_PATH}').result())

        logger.info("------------------standyby delete data file----------------------")
        deleteCmd = f'mv {self.basefile} {self.basefilebak}'
        logger.info(deleteCmd)
        self.dbStandby1UserNode.sh(deleteCmd)
        logger.info(self.dbStandby1UserNode.sh(
            f'ls -al {macro.DB_INSTANCE_PATH}').result())

        logger.info("-----------build standby-----------")
        result = self.standby_1_sh.buildStandby()
        logger.info(result)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, result)

        time.sleep(5)

        logger.info("-------------standyby damage data file ----------")
        baselistCmd = f'ls -a {self.basefile}/*/*'
        baselist = self.dbStandby1UserNode.sh(baselistCmd).result()
        for i in baselist.split('\n'):
            self.dbStandby1UserNode.sh(f'>{i}').result()

        logger.info("-----------build standby-----------")
        result = self.standby_1_sh.buildStandby()
        logger.info(result)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, result)

        time.sleep(5)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("------------------------recover conf file------------------")
        list = self.dbStandby1UserNode.sh(
            f'ls -al {macro.DB_INSTANCE_PATH}').result()
        if '.baktest' in list:
            recoverCmd = f'rm -f {self.conffile}'
            logger.info(recoverCmd)
            self.dbStandby1UserNode.sh(recoverCmd)
            recoverCmd = f'mv {self.conffilebak} {self.conffile}'
            logger.info(recoverCmd)
            self.dbStandby1UserNode.sh(recoverCmd)

        logger.info("========判断备机是否需要重建=====")
        result = self.commonsh_user.check_whether_need_build()
        if result:
            result = self.standby_1_sh.buildStandby()
            logger.info(result)
            result = self.standby_2_sh.buildStandby()
            logger.info(result)